<?php
namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;

use Think\Log;
use Think\Model;

class PositionModel {
    //根据county_id获取city_id
    public function getCityIDByCountyID($county_id){
        return M('PositionCounty')->where(['county_id' => $county_id])->field('city_id')->find();
    }

    //根据city_id获取province_id
    public function getProvinceIDByCityID($city_id){
        return M('PositionCity')->where(['city_id' => $city_id])->field('province_id')->find();
    }

    //根据county_id获取province_id
    public function getProvinceIDByCountyID($county_id){
        $city_id = $this->getCityIDByCountyID($county_id);
        return $this->getProvinceIDByCityID($city_id['city_id']);
    }

    //获取某个省下所有的county_id
    public function getAllCountyIdByProviceId($provice_id)
    {
        $sql = 'SELECT
                    cc.county_id
                FROM
                    position_provice p
                LEFT JOIN position_city c ON p.provice_id = c.province_id
                LEFT JOIN position_county cc ON cc.city_id = c.city_id
                WHERE
                    p.provice_id = '.$provice_id;
        Log::write("sql=".$sql, Log::DEBUG);

        $county_id_arr = M()->query($sql);
        $county_id_str = '';
        foreach ($county_id_arr as $v){
            $county_id_str .= $v['county_id'].", ";
        }
        Log::write("county_id_arr=".json_encode($county_id_arr).", county_id_str=".substr($county_id_str, 0, strlen($county_id_str)-2), Log::DEBUG);

        return substr($county_id_str, 0, strlen($county_id_str)-2);
    }

    //根据county_name获取对应的county_id值
    public function getCountyIDByCountyName($provice_name, $county_name){
        $county_id = '';
        $county_ids = M('PositionCounty')->where(['county_name'=>$county_name])->select();
        if($county_ids){
            if(count($county_ids) == 1){
                $county_id = $county_ids[0]['county_id'];
            }else{
                //查询省份id
                if($provice_name){
                    $provice_id = M('PositionProvice')->where(['provice_name'=>$provice_name])->find();
                    Log::write("sql=".M('PositionProvice')->getLastSql()." res=".json_encode($provice_id), Log::DEBUG);
                    foreach ($county_ids as $v){
                        Log::write("substr=".substr($v['county_id'], 0, 3).', provice_id='.$provice_id['provice_id'], Log::DEBUG);
                        if(substr($v['county_id'], 0, 2) == substr($provice_id['provice_id'], 0, 2)){
                            $county_id = $v['county_id'];
                            break;
                        }
                    }
                }
            }
        }

        return $county_id;
    }
}
